package cloud.xlh.middleware_manage.util;

import com.jcraft.jsch.ChannelExec;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/8/5 17:02
 * @ Description:
 */
public class SFTPUtil {
    //ip地址
    private String host;
    //登录账号
    private String username;
    //登录密码
    private String password;
    //默认端口号
    private int port;
    //默认过期时间
    private int timeout;

    public SFTPUtil(String host , String username , String password , int port , int timeout) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
        this.timeout = timeout;
    }


    public void executeCmd(byte[] cmdByte) {
        SFTPChannel sftpChannel = new SFTPChannel(host, username, password , port , timeout);
        ChannelExec channelExec = null;
        try {
            channelExec = sftpChannel.getChannel(sftpChannel);
            channelExec.setCommand(cmdByte);
            // 获取命令执行的输出流
            InputStream in = channelExec.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            StringBuilder result = new StringBuilder();
            channelExec.connect();
            // 读取命令执行的输出结果
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
            // 输出命令执行结果
            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sftpChannel.closeChannel();
        }


    }
}
